
package com.insigma.business.qrcode.soldier._provider.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.insigma.business.qrcode.common.converter.SoldierApplyInfoProviderConverter;
import com.insigma.business.qrcode.common.dao.CommonAdminAreaDO;
import com.insigma.business.qrcode.common.dto.SoldierApplyTypeEnum;
import com.insigma.business.qrcode.common.dto.SoldierTypeEnum;
import com.insigma.business.qrcode.common.service.CommonAdminAreaService;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.util.*;
import com.insigma.business.qrcode.soldier._provider.*;
import com.insigma.business.qrcode.soldier.dto.*;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.common.vo.ProcessStatusEnum;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.soldier.request.*;
import com.insigma.business.qrcode.soldier.service.impl.SoldierBasicRefresher;
import com.insigma.business.qrcode.soldier.util.PrivacyEncUtils;
import com.insigma.business.qrcode.soldier.util.ResponseUtils;
import com.insigma.business.qrcode.soldier.service.*;
import com.insigma.business.qrcode.soldier.util.ThreadPoolManager;
import com.insigma.framework.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.MDC;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.insigma.business.qrcode.common.dto.ErrorCodeEnum;


import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
@Component("soldierApplyInfoProvider")
public class SoldierApplyInfoProviderImpl extends BaseProviderImpl implements SoldierApplyInfoProvider {

    @Autowired
    private SoldierApplyInfoService soldierApplyInfoService;

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CommonAdminAreaService commonAdminAreaService;

    @Autowired
    SoldierApplyCheckService soldierApplyCheckService;

    @Autowired
    private SoldierBasicRefresher soldierBasicRefresher;

    @Autowired
    private SoldierOuterBasicInfoService soldierOuterBasicInfoService;

    @Autowired
    private SoldierOuterLoginAccountService soldierOuterLoginAccountService;
    @Autowired
    private AliShhProvider aliShhProvider;

    @Autowired
    GovEmployeeRoleProvider govEmployeeRoleProvider;

    @Autowired
    GovOrgProvider govOrgProvider;

    @Resource
    private BasicInformationService basicInformationService;

    private Integer maxApplyCount = 5;

    @Override
    public BaseResponse<String> deleteCzSoldier(ImportCzApiRequest request) {
        try {
            String url = request.getUrl();
            url = url.replace("115.227.32.11", "172.18.102.62");
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            final List<List<Object>> read = reader.read();

            List<Object> objects = read.get(0);
            BizCheckUtil.checkIsTrue(((String) objects.get(0)).startsWith("*居住区域(区/县)"), "模板错误");
            BizCheckUtil.checkIsTrue(((String) objects.get(1)).startsWith("*居住区域(街道/镇)"), "模板错误");
            BizCheckUtil.checkIsTrue(((String) objects.get(2)).startsWith("*居住区域(社区/村)"), "模板错误");
            BizCheckUtil.checkIsTrue(((String) objects.get(3)).startsWith("*姓名"), "模板错误");
            BizCheckUtil.checkIsTrue(((String) objects.get(4)).startsWith("*身份证号"), "模板错误");

            List<List<Object>> list = read.subList(1, read.size());
            log.info("校验模板成功，获取数据===="+list.size());
            String traceId = MDC.get("traceId");
            ThreadPoolManager.getInstance().submit(new Runnable() {
                @Override
                public void run() {
                    log.info("获取数据====开始:");
                    String result = "删除老兵结果：\n";
                    MDC.put("traceId", Strings.isBlank(traceId) ? UUID.randomUUID().toString() : traceId);
                    for (List<Object> objects : list) {
                        log.info("删除老兵：{}", objects);
                        String residentCountyValue = (String) objects.get(0);//居住区
                        String residentTownValue = (String) objects.get(1);//居住镇
                        String residentVillageValue = (String) objects.get(2);//居住村
                        String name = (String) objects.get(3);
                        String idCard = (String) objects.get(4);
                        if (Strings.isBlank(idCard) || Strings.isBlank(name) || Strings.isBlank(residentVillageValue)) {
                            continue;
                        }
                        String areaCode="";
                        if(StringUtil.isNotEmpty(residentVillageValue)){
                            List<CommonAdminAreaDO> listAreaHz = commonAdminAreaService.getSubAreaByValue(residentVillageValue);
                            if(listAreaHz != null && listAreaHz.size()>0){
                                areaCode = listAreaHz.get(0).getId();
                            }
                        }
                        if(StringUtil.isNotEmpty(areaCode)){
                            List<SoldierApplyInfoDO>  applyInfoDOList= soldierApplyInfoService.getByIdCardAndAreaCode(idCard,areaCode);
                            if(applyInfoDOList != null && applyInfoDOList.size()>0){
                                for(SoldierApplyInfoDO soldierApplyInfoDO : applyInfoDOList){
                                    soldierApplyCheckService.delete(soldierApplyInfoDO.getId());
                                    soldierApplyInfoService.delete(soldierApplyInfoDO.getId(),"导入删除",request.getId());
                                }
                                log.info("导入删除成功！！");
                            }
                        }else{
                            result += addResultStr("居住区域(社区/村)不能为空", name, idCard);
                            continue;
                        }
                    }
                    log.info("{}", result);
                }
            });
        } catch (BizException e) {
            log.error("导入数据发生异常", e);
            throw e;
        } catch (Exception e) {
            log.error("导入数据发生异常", e);
            throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM);
        }
        return ResponseUtils.buildSuccessResponse("处理中");
    }

    @Override
    public BaseResponse<String> insertCzSoldier(ImportCzApiRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");
        BizCheckUtil.checkNotNull(request.getCreatorId(), "用户不能为空");

        try {
            String url = request.getUrl();
            url = url.replace("115.227.32.11", "172.18.102.62");
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            log.info("开始读取文件");
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            final List<List<Object>> read = reader.read();
            String[] strings = {"*姓名", "*性别", "*身份证号", "*手机号", "*居住区域(区/县)", "*居住区域(街道/镇)", "*居住区域(社区/村)", "*户籍地址(省/直辖市/自治区)","*户籍地址(地级市/自治州/盟)"};
            checkSoldierImportTemplate(read.get(0), strings);
            log.info("校验模板成功");
            ThreadPoolManager.getInstance().submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        log.info("获取list");
                        List<List<Object>> list = read.subList(1, read.size());
//                            for (List<Object> objects : list) {
//                                for (int i = objects.size(); i < strings.length; i++) {
//                                    objects.add(null);
//                                }
//                            }
                        log.info("开始循环list");
                        for (List<Object> objects : list) {
                            String name = (String) objects.get(0);
                            String gender = (String) objects.get(1);
                            String idCard = (String) objects.get(2);
                            String phone = objects.get(3)+"";
                            String residentCountyValue = (String) objects.get(4);//居住区
                            String residentTownValue = (String) objects.get(5);//居住村
                            String residentVillageValue = (String) objects.get(6);//居住街道
                            String rootProvinceValue = (String) objects.get(7);//籍贯县级行政区划中文
                            String rootCountyValue = (String) objects.get(8);//籍贯乡级行政区划中文
                            log.info("开始校验参数判断："+idCard);
                            if (Strings.isBlank(idCard) || Strings.isBlank(name) || Strings.isBlank(residentCountyValue) || Strings.isBlank(residentTownValue) || Strings.isBlank(residentVillageValue) ||
                                    Strings.isBlank(rootProvinceValue) || Strings.isBlank(rootCountyValue)) {
                                continue;
                            }
                            log.info("打印参数rootCountyValue"+rootCountyValue);
                            SoldierApplyInfoDO soldierApplyInfoDO = new SoldierApplyInfoDO();
                            soldierApplyInfoDO.setRealName(name);
                            soldierApplyInfoDO.setGender(gender.equals("男") ? "MALE" : "FEMALE");
                            log.info("身份证号码："+idCard);
                            soldierApplyInfoDO.setIdCardNo(PrivacyEncUtils.encodeIdCardNo(idCard));
                            soldierApplyInfoDO.setMobile(phone);
                            soldierApplyInfoDO.setResidentAdminAreaCode(rootCountyValue); //居住地行政区划
                            if(StringUtil.isNotEmpty(rootCountyValue)){
                                List<CommonAdminAreaDO> listArea = commonAdminAreaService.getAllSubAreaOfQgByValue(rootCountyValue);
                                if(listArea != null && listArea.size()>0){
                                    soldierApplyInfoDO.setRootAdminAreaCode(listArea.get(0).getId());   //户籍地code
                                }
                            }
                            log.info("打印参数rootCountyValue"+rootCountyValue);
                            if(StringUtil.isNotEmpty(residentVillageValue)){
                                List<CommonAdminAreaDO> listAreaHz = commonAdminAreaService.getSubAreaByValue(residentVillageValue);
                                if(listAreaHz != null && listAreaHz.size()>0){
                                    soldierApplyInfoDO.setResidentAdminAreaCode(listAreaHz.get(0).getId());
                                }
                            }
                            log.info("打印参数rootCountyValue"+rootCountyValue);
                            log.info("居住地打印"+"/"+residentCountyValue+"/"+residentTownValue+"/"+residentVillageValue);
                            soldierApplyInfoDO.setResidentAddress("/"+residentCountyValue+"/"+residentTownValue+"/"+residentVillageValue);
                            log.info("户籍地打印"+"/"+rootProvinceValue+"/"+rootCountyValue);
                            soldierApplyInfoDO.setRootAddress("/"+rootProvinceValue+"/"+rootCountyValue);
                            soldierApplyInfoDO.setCreatorId(request.getCreatorId());
                            soldierApplyInfoDO.setIsOnline("1");//导入默认线下申请
                            soldierApplyInfoDO.setCreateDatetime(new Date());
                            soldierApplyInfoDO.setStatus("SUCCESS");
                            soldierApplyInfoDO.setIsPush("0");
                            soldierApplyInfoDO.setApplyType("OUTSIDER");
                            //查询是否导入过杭籍老兵
                            log.info("查询身份证参数是加密还是不加密"+idCard);
                            SoldierApplyInfoDO soldierApplyInfoDONew = soldierApplyInfoService.getByIdCardInfo(idCard);
                            log.info("判断是新增还是更新");
                            if(soldierApplyInfoDONew != null){
                                log.info("进入更新方法");
                                //更新
                                soldierApplyInfoDO.setId(soldierApplyInfoDONew.getId());
                                soldierApplyInfoService.update(soldierApplyInfoDO);
                                log.info("更新成功");
                            }else{
                                log.info("进入新增方法");
                                //新增
                                soldierApplyInfoDO.setSoldierType("退役军人");
                                soldierApplyInfoDO.setSoldierTypeDictCode("VETERANS_SOLDIER");
                                soldierApplyInfoService.insert(soldierApplyInfoDO);
                                log.info("新增成功");
                            }
                        }
                    } catch (Exception e) {
                        log.error("导入错误：{}", e);
                    }
                }
            });

        } catch (BizException e) {
            log.error("导入数据发生异常", e);
            throw e;
        } catch (Exception e) {
            log.error("导入数据发生异常", e);
            throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM);
        }
        return ResponseUtils.buildSuccessResponse("处理中");
    }

    @Override
    public BaseResponse<ExcelResultBO> querySoldierManualCheckDealStatsExcel(SimpleApiRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");

        List<DataStatsCDO> allItem = soldierApplyInfoService.querySoldierManualStats(request.getAdminAreaCode(), null, request.getBeginDate(), request.getEndDate());
        List<DataStatsCDO> dealingItem = soldierApplyInfoService.querySoldierManualStats(request.getAdminAreaCode(), ProcessStatusEnum.DEALING.name(), request.getBeginDate(), request.getEndDate());
        List<DataStatsCDO> successItem = soldierApplyInfoService.querySoldierManualStats(request.getAdminAreaCode(), ProcessStatusEnum.SUCCESS.name(), request.getBeginDate(), request.getEndDate());
        List<DataStatsCDO> rejectItem = soldierApplyInfoService.querySoldierManualStats(request.getAdminAreaCode(), ProcessStatusEnum.REJECT.name(), request.getBeginDate(), request.getEndDate());

        List<String> headers = Lists.newArrayList("地区", "处理中", "处理成功", "驳回", "总计", "处理率");
        List<List<String>> data = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(allItem)) {
            for (DataStatsCDO dataStatsCDO : allItem) {
                List<String> itemEx = Lists.newArrayList();
                itemEx.add(dataStatsCDO.getItemName());
                itemEx.add(getCount(dataStatsCDO.getItemName(), dealingItem));
                itemEx.add(getCount(dataStatsCDO.getItemName(), successItem));
                itemEx.add(getCount(dataStatsCDO.getItemName(), rejectItem));
                itemEx.add(String.valueOf(dataStatsCDO.getItemCount()));
                itemEx.add(getProPortion(dataStatsCDO.getItemCount() - Integer.valueOf(getCount(dataStatsCDO.getItemName(), dealingItem)), dataStatsCDO.getItemCount()));
                data.add(itemEx);
            }
            if ("330100000000".equals(request.getAdminAreaCode())) {
                Collections.sort(data, new Comparator<List<String>>() {
                    @Override
                    public int compare(List<String> o1, List<String> o2) {
                        return getIndexOfLike(o1.get(0), HeroConstant.DISTRICT_SORT_LIST).compareTo(getIndexOfLike(o2.get(0), HeroConstant.DISTRICT_SORT_LIST));
                    }
                });
            }

            List<String> zj = Lists.newArrayList("总计", String.valueOf(countAll(dealingItem)), String.valueOf(countAll(successItem)),
                    String.valueOf(countAll(rejectItem)), String.valueOf(countAll(allItem)),
                    getProPortion((countAll(allItem) - countAll(dealingItem)), countAll(allItem)));
            data.add(zj);
        }

        return ResponseUtils.buildSuccessResponse(new ExcelResultBO("手动审核老兵码处理情况统计", headers, data));
    }

    private Integer countAll(List<DataStatsCDO> list) {
        int i = 0;
        for (DataStatsCDO dataStatsCDO : list) {
            i += dataStatsCDO.getItemCount();
        }
        return i;
    }
    private String getCount(String itemName, List<DataStatsCDO> dealingItem) {
        for (DataStatsCDO dataStatsCDO : dealingItem) {
            if (dataStatsCDO.getItemName().equals(itemName)) {
                return String.valueOf(dataStatsCDO.getItemCount());
            }
        }
        return "0";
    }

    @Override
    public BaseResponse<ExcelResultBO> querySoldierManualCheckDetailExcel(SimpleApiRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");

        List<Map<String, Object>> list = soldierApplyInfoService.querySoldierManualCheckDetail(request.getAdminAreaCode(), request.getBeginDate(), request.getEndDate());
        List<String> headers = Lists.newArrayList("姓名", "地区", "状态", "代持", "审核意见", "提交时间", "审核时间");
        List<List<String>> data = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (Map<String, Object> map : list) {
                List<String> item = Lists.newArrayList();
                item.add((String) map.get("姓名"));
                item.add((String) map.get("地区"));
                item.add((String) map.get("状态"));
                item.add((Boolean) map.get("代持") ? "是" : "否");
                item.add((String) map.get("审核意见"));
                item.add(getDateString((Date) map.get("提交时间")));
                item.add(getDateString((Date) map.get("审核时间")));
                data.add(item);
            }
        }

        if ("330100000000".equals(request.getAdminAreaCode())) {
            Collections.sort(data, new Comparator<List<String>>() {
                @Override
                public int compare(List<String> o1, List<String> o2) {
                    return getIndexOfLike(o1.get(1), HeroConstant.DISTRICT_SORT_LIST).compareTo(getIndexOfLike(o2.get(1), HeroConstant.DISTRICT_SORT_LIST));
                }
            });
        }

        return ResponseUtils.buildSuccessResponse(new ExcelResultBO("手动审核老兵码统计", headers, data));
    }

    private String getDateString(Date date) {
        return DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");

    }

    @Override
    public BaseResponse<ExcelResultBO> querySoldierCunQrStatsExcel(SimpleApiRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");
        List<DataStatsCDO> allStats = soldierBasicInfoService.queryAreaSoldierQrStats(request.getAdminAreaCode(), 0, request.getBeginDate(), request.getEndDate());
        List<DataStatsCDO> qrStats = soldierBasicInfoService.queryAreaSoldierQrStats(request.getAdminAreaCode(), 1, request.getBeginDate(), request.getEndDate());

        List<String> headers = Lists.newArrayList("地区（部分数据由于采集信息不准确，只能将部分人员划分到区县街道）", "总人数", "已申领人数", "比例");
        List<List<String>> data = Lists.newArrayList();
        Map<String, Integer> qrStatsMap = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(qrStats)) {
            for (DataStatsCDO qrStat : qrStats) {
                qrStatsMap.put(qrStat.getItemName(), qrStat.getItemCount());
            }
        }
        for (DataStatsCDO allStat : allStats) {
            String area = allStat.getItemName();
            Integer integer = qrStatsMap.get(area);
            int intQrStats = integer == null ? 0 : integer;
            Integer itemCount = allStat.getItemCount();
            data.add(Lists.newArrayList(area, String.valueOf(itemCount), String.valueOf(intQrStats), getProPortion(intQrStats, itemCount)));
        }


        return ResponseUtils.buildSuccessResponse(new ExcelResultBO("老兵按村统计", headers, data));
    }

    @Override
    public BaseResponse<ExcelResultBO> queryQRSuccessExcel(SimpleApiRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");

        List<DataStatsCDO> successResult = soldierBasicInfoService.querySoldierQrSuccessResult(request.getAdminAreaCode(), request.getBeginDate(), request.getEndDate());
        List<DataStatsCDO> allPerson = soldierBasicInfoService.queryAllSoldierResult(request.getAdminAreaCode(), request.getBeginDate(), request.getEndDate());
        if ("330100000000".equals(request.getAdminAreaCode())) {
            Collections.sort(allPerson, new Comparator<DataStatsCDO>() {
                @Override
                public int compare(DataStatsCDO o1, DataStatsCDO o2) {
                    return getIndexOfLike(o1.getItemName(), HeroConstant.DISTRICT_SORT_LIST).compareTo(getIndexOfLike(o2.getItemName(), HeroConstant.DISTRICT_SORT_LIST));
                }
            });
        }
        List<String> headers = Lists.newArrayList("地区", "人口总数", "已申领人数", "比例");
        List<List<String>> data = Lists.newArrayList();
        Map<String, DataStatsCDO> qrSuccessMap = successResult.stream().collect(Collectors.toMap(DataStatsCDO::getItemName, s -> s));
        for (DataStatsCDO person : allPerson) {
            List<String> item = Lists.newArrayList();
            item.add(person.getItemName());
            Integer allCount = person.getItemCount();
            item.add(String.valueOf(allCount));
            DataStatsCDO qrSuccessItem = qrSuccessMap.get(person.getItemName());
            if (qrSuccessItem != null) {
                Integer qrSuccessCount = qrSuccessItem.getItemCount();
                item.add(String.valueOf(qrSuccessCount));
                item.add(String.valueOf(getProPortion(qrSuccessCount, allCount)));
            }
            data.add(item);
        }
        Integer countAll = soldierBasicInfoService.countSoldier(AdminAreaCodeUtils.getCutdAreaCode(request.getAdminAreaCode()) + "%", request.getBeginDate(), request.getEndDate());
        Integer countQR = soldierBasicInfoService.countQrSuccessByArea(AdminAreaCodeUtils.getCutdAreaCode(request.getAdminAreaCode()) + "%", request.getBeginDate(), request.getEndDate());
        int countQrInt = countQR == null ? 0 : countQR;
        data.add(Lists.newArrayList("总计", String.valueOf(countAll), String.valueOf(countQrInt), getProPortion(countQrInt, countAll)));

        return ResponseUtils.buildSuccessResponse(new ExcelResultBO("老兵码申请情况", headers, data));
    }

    private String getProPortion(Integer dividend, Integer divisor) {
        if (dividend == null || divisor == null) {
            return "0";
        }
        double v = 100.0 * dividend / divisor;
        return String.format("%.2f", v);
    }

    private Integer getIndexOfLike(String itemCNName, List<String> sortKeyList) {
        if (Strings.isBlank(itemCNName)) {
            return sortKeyList.size();
        }

        for (int i = 0; i < sortKeyList.size(); i++) {
            if (itemCNName.contains(sortKeyList.get(i))) {
                return i;
            }
        }
        return sortKeyList.size();
    }

    @Transactional
    @Override
    public BaseResponse<String> saveSoldierApplyInfo(SoldierApplyInfoInsertRequest request) {
        //校验保存入参
        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode().trim(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        BizCheckUtil.checkNotNull(request.getAttachment(), "附件不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierTypeDictCode(), "老兵类型不能为空");
        BizCheckUtil.checkNotBlank(request.getRealName(), "姓名不能为空");
        BizCheckUtil.checkNotBlank(request.getMobile());
        if (Boolean.TRUE.equals(request.getHolded())) {
            BizCheckUtil.checkNotNull(request.getHoldIdCardNo(), "证件号码不能为空");
        } else {
            BizCheckUtil.checkNotNull(request.getIdCardNo(), "证件号码不能为空");
        }

        //校验居住地行政区划编码
        String residentAdminAreaCode = request.getResidentAdminAreaCode();
        int level = AdminAreaCodeUtils.getLevel(residentAdminAreaCode);
        BizCheckUtil.checkIsTrue(level == 5, "请将行政区划选择到村社一级");

        //校验该soldierId是否存在军人基础信息
        SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getBySoldierId(request.getSoldierId());
        BizCheckUtil.checkNotNull(soldierBasicInfoDO, "军人基础信息不存在");
        //校验证件号码是否存在军人基础信息



        //校验该soldierId是否已申请老兵码
        SoldierApplyInfoDO soldierApplyInfoExistsDO = soldierApplyInfoService.getBySoldierId(request.getSoldierId());
        if (soldierApplyInfoExistsDO != null && (ProcessStatusEnum.SUCCESS.name().equals(soldierApplyInfoExistsDO.getStatus()) || ProcessStatusEnum.DEALING.name().equals(soldierApplyInfoExistsDO.getStatus()))) {
            throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR, "该用户已申请老兵码");
        }

        //校验该证件号码是否已申请老兵码
        SoldierApplyInfoDO oldApplyDO = soldierApplyInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkIsNull(oldApplyDO, "该证件号码已申请老兵码");

        final SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestIO2DO(request);
        soldierApplyInfoDO.setManualCheck(true);
        soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEALING.name());
        soldierApplyInfoDO.setCount(1);
        soldierApplyInfoService.insert(soldierApplyInfoDO);
        return ResponseUtils.buildSuccessResponse(soldierApplyInfoDO.getId());
    }

    @Override
    public BaseResponse<String> checkSoldierApplyInfoBySoldierId(String soldierId) {
        BizCheckUtil.checkNotBlank(soldierId, "soldierId不能为空");
        SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.getBySoldierId(soldierId);
        if (soldierApplyInfoDO != null) {
            throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR, "该用户已申请老兵码");
        }
        return ResponseUtils.buildSuccessResponse("操作成功");
    }

    @Transactional
    @Override
    public BaseResponse<String> saveSoldierApplyInfoOfOuterTemporary(SoldierApplyInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierType(), "老兵类型不能为空");
        BizCheckUtil.checkNotBlank(request.getRealName(), "姓名不能为空");
        BizCheckUtil.checkNotBlank(request.getMobile(), "手机号不为空");
        BizCheckUtil.checkIDCardNO(request.getIdCardNo());

        int count = 1;
        List<SoldierApplyInfoDO> soldierApplyInfoDOS = soldierApplyInfoService.listBySoldierId(request.getSoldierId(), SoldierApplyTypeEnum.TEMPORARY.name());
        if (!CollectionUtils.isEmpty(soldierApplyInfoDOS)) {
            BizCheckUtil.checkIsTrue(soldierApplyInfoDOS.size() <= 3, "申请次数不大于3次");
            count = count + soldierApplyInfoDOS.size();
        }


        final SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestIO2DO(request);
        soldierApplyInfoDO.setStatus(ProcessStatusEnum.SUCCESS.name());
        soldierApplyInfoDO.setApplyType(SoldierApplyTypeEnum.TEMPORARY.name());
        soldierApplyInfoDO.setCount(count);
        soldierApplyInfoDO.setManualCheck(true);
        soldierApplyInfoService.insert(soldierApplyInfoDO);

        return ResponseUtils.buildSuccessResponse(soldierApplyInfoDO.getId());
    }

    @Override
    public BaseResponse<Integer> getRemainingTimesOfOuterTemporary(String soldierId) {

        BizCheckUtil.checkNotNull(soldierId, "request的请求参数不能为空");
        List<SoldierApplyInfoDO> soldierApplyInfoDOS = soldierApplyInfoService.listBySoldierId(soldierId, SoldierApplyTypeEnum.TEMPORARY.name());
        int remaining = 3;
        if (!CollectionUtils.isEmpty(soldierApplyInfoDOS)) {
            remaining = remaining - soldierApplyInfoDOS.size();
        }
        return ResponseUtils.buildSuccessResponse(remaining);
    }


    @Transactional
    @Override
    public BaseResponse<String> saveSoldierApplyInfoOfOutsider(SoldierApplyInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode().trim(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotBlank(request.getRealName(), "姓名不能为空");
        BizCheckUtil.checkNotBlank(request.getMobile());
        BizCheckUtil.checkIDCardNO(request.getIdCardNo());

        List<SoldierApplyInfoDO> soldierApplyInfoDOS = soldierApplyInfoService.listBySoldierId(request.getSoldierId(), SoldierApplyTypeEnum.OUTSIDER.name());
        if (!CollectionUtils.isEmpty(soldierApplyInfoDOS)) {
            return ResponseUtils.buildFailResponse(ErrorCodeEnum.ERROR_USER_ALREADY_APPLY);
        }

        final SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestIO2DO(request);
        soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEALING.name());
        soldierApplyInfoDO.setApplyType(SoldierApplyTypeEnum.OUTSIDER.name());
        soldierApplyInfoDO.setManualCheck(true);
        soldierApplyInfoDO.setCount(1);
        soldierApplyInfoService.insert(soldierApplyInfoDO);

        return ResponseUtils.buildSuccessResponse(soldierApplyInfoDO.getId());
    }

    @Transactional
    @Override
    public BaseResponse<String> reApplySoldierQROfOutsider(SoldierApplyInfoUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode().trim(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotBlank(request.getRealName(), "姓名不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierTypeDictCode(), "老兵类型不能为空");
        BizCheckUtil.checkNotBlank(request.getMobile());
        BizCheckUtil.checkIDCardNO(request.getIdCardNo());

        List<SoldierApplyInfoDO> soldierApplyInfoDOS = soldierApplyInfoService.listBySoldierId(request.getSoldierId(), SoldierApplyTypeEnum.OUTSIDER.name());
        if (CollectionUtils.isEmpty(soldierApplyInfoDOS)) {
            final SoldierApplyInfoDO soldierApplyInfoDO = new SoldierApplyInfoDO();
            BeanUtils.copyProperties(request, soldierApplyInfoDO);
            soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEALING.name());
            soldierApplyInfoDO.setApplyType(SoldierApplyTypeEnum.OUTSIDER.name());
            soldierApplyInfoDO.setManualCheck(true);
            soldierApplyInfoDO.setCount(1);
            soldierApplyInfoService.insert(soldierApplyInfoDO);
            return ResponseUtils.buildSuccessResponse(soldierApplyInfoDO.getId());
        }

        SoldierApplyInfoDO applyInfoDO = soldierApplyInfoDOS.get(0);
        if (!applyInfoDO.getStatus().equals(ProcessStatusEnum.REJECT.name())) {
            return ResponseUtils.buildFailResponse(String.valueOf(ErrorCodeEnum.ILLEGAL_PARAM), "审核结果不是驳回");
        }

        if (applyInfoDO.getCount() > maxApplyCount) {
            return ResponseUtils.buildFailResponse(ErrorCodeEnum.ERROR_USER_ALREADY_APPLY_OVERRUN);
        }

        if (!request.getIdCardNo().equals(applyInfoDO.getIdCardNo())) {
            SoldierApplyInfoDO oldApplyDO = soldierApplyInfoService.getByIdCardNo(request.getIdCardNo());
            if (oldApplyDO != null) {
                return ResponseUtils.buildFailResponse(String.valueOf(ErrorCodeEnum.ERROR_APPLY_IDCARD_SAME), "此身份证已经申请");
            }
        }


        final SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestUO2DO(request);
        soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEALING.name());
        soldierApplyInfoDO.setApplyType(SoldierApplyTypeEnum.OUTSIDER.name());
        soldierApplyInfoDO.setId(applyInfoDO.getId());
        soldierApplyInfoDO.setCount(applyInfoDO.getCount() + 1);
        soldierApplyInfoDO.setManualCheck(true);
        //先删除审核流程再重新提交
        log.info("删除审核流程");
        soldierApplyCheckService.delete(soldierApplyInfoDO.getId());
        log.info("审核流程删除成功");
        soldierApplyInfoService.update(soldierApplyInfoDO);
        return ResponseUtils.buildSuccessResponse(soldierApplyInfoDO.getId());
    }

    @Override
    public BaseResponse<String> updateApplyInfoOfOutsider(SoldierApplyInfoUpdateRequest request) {
        return null;
    }


    @Transactional
    @Override
    public BaseResponse<String> saveSoldierApplyInfoByFWZ(SoldierApplyInfoInsertRequest request) {
        BizCheckUtil.checkNotNull(request, "新增CareSoldierDemand的请求参数不能为空");
        BizCheckUtil.checkNotNull(request.getResidentAdminAreaCode(), "地区不能为空");

        SoldierBasicInfoDO baseInfo = soldierBasicInfoService.getSoldierBasicInfoByCard(request.getIdCardNo(), request.getRealName());
        if (baseInfo != null) {
            return ResponseUtils.buildFailResponse("系统中已存在身份证");
        }

        baseInfo = new SoldierBasicInfoDO();
        BeanUtils.copyProperties(request, baseInfo);
        baseInfo.setSoldierId(request.getSoldierId());
        baseInfo.setResidentAdminAreaCode(request.getResidentAdminAreaCode());
        baseInfo.setResidentAddress(request.getResidentAddress());
        baseInfo.setMobile(request.getMobile());
        baseInfo.setSoldierTypeDictCode(request.getSoldierTypeDictCode());
        baseInfo.setCreateDatetime(new Date());
        baseInfo.setSoldierType(request.getSoldierType());
        baseInfo.setManual(true);
        soldierBasicInfoService.insert(baseInfo);

        return ResponseUtils.buildSuccessResponse(baseInfo.getId());
    }

    @Override
    public BaseResponse<SoldierApplyInfoDTO> getSoldierApplyInfo(String id) {
        BizCheckUtil.checkNotNull(id, "请求参数不能为空");
        final SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.get(id);
        final SoldierApplyInfoDTO remoteObj = SoldierApplyInfoProviderConverter.convertResponseDO2DTO(soldierApplyInfoDO);
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BaseResponse<SoldierApplyInfoDTO> getSoldierApplyInfoById(String id) {
        BizCheckUtil.checkNotNull(id, "ID不能为空");

        final SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.get(id);
        BizCheckUtil.checkNotNull(soldierApplyInfoDO, "查无此人");
        final SoldierApplyInfoDTO remoteObj = SoldierApplyInfoProviderConverter.convertResponseDO2DTO(soldierApplyInfoDO);
        //查询数据采集信息(优待证信息)
        BasicInformationDO qBasicInformationDO = new BasicInformationDO();
        qBasicInformationDO.setIdCard(remoteObj.getIdCardNo());
        List<BasicInformationDO> basicInformationList = basicInformationService.queryBasicInformationList(qBasicInformationDO);
        if (!CollectionUtils.isEmpty(basicInformationList)) {
            BasicInformationDTO basicInformationDTO = new BasicInformationDTO();
            BeanUtils.copyProperties(basicInformationList.get(0), basicInformationDTO);
            remoteObj.setBasicInformationDTO(basicInformationDTO);
        }

        if (Strings.isBlank(remoteObj.getResidentAddress()) && Strings.isNotBlank(remoteObj.getResidentAdminAreaCode())) {
            CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(remoteObj.getResidentAdminAreaCode());
            remoteObj.setResidentAddress(commonAdminAreaDO.getFullValuePath());
        }
        if (Strings.isBlank(remoteObj.getRootAddress()) && Strings.isNotBlank(remoteObj.getRootAdminAreaCode())) {
            String fullValuePath = commonAdminAreaService.getQgFullValuePath(remoteObj.getRootAdminAreaCode());
            remoteObj.setRootAddress(fullValuePath);
        }

        SoldierBasicInfoDO baseDo = soldierBasicInfoService.get(soldierApplyInfoDO.getIdCardNo());
        if (baseDo != null) {
            remoteObj.setIfInDb(Boolean.TRUE);
        } else {
            remoteObj.setIfInDb(Boolean.FALSE);
        }

        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BaseResponse<SoldierApplyInfoDTO> getSoldierApplyInfoBySoldierId(String soldierId) {
        BizCheckUtil.checkNotBlank(soldierId);
        SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.getLastApplyOfSoldierId(soldierId, null);

        final SoldierApplyInfoDTO remoteObj = SoldierApplyInfoProviderConverter.convertResponseDO2DTO(soldierApplyInfoDO);
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Transactional
    @Override
    public BaseResponse<String> reApplySoldierQR(SoldierApplyInfoUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode().trim(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotBlank(request.getRealName(), "姓名不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierTypeDictCode(), "老兵类型不能为空");
        BizCheckUtil.checkNotBlank(request.getMobile());
        BizCheckUtil.checkIDCardNO(request.getIdCardNo());

        SoldierApplyInfoDO applyInfoBySoldierId = soldierApplyInfoService.getBySoldierId(request.getSoldierId());
        if (applyInfoBySoldierId == null) {
            return ResponseUtils.buildFailResponse(String.valueOf(ErrorCodeEnum.ERROR_USER_ALREADY_APPLY), "还未提交申请");
        }

        if (!applyInfoBySoldierId.getStatus().equals(ProcessStatusEnum.REJECT.name())) {
            return ResponseUtils.buildFailResponse(String.valueOf(ErrorCodeEnum.ILLEGAL_PARAM), "审核结果不是驳回");
        }

        if (applyInfoBySoldierId.getCount() > maxApplyCount) {
            return ResponseUtils.buildFailResponse(ErrorCodeEnum.ERROR_USER_ALREADY_APPLY_OVERRUN);
        }

        if (!request.getIdCardNo().equals(applyInfoBySoldierId.getIdCardNo())) {
            SoldierApplyInfoDO oldApplyDO = soldierApplyInfoService.getByIdCardNo(request.getIdCardNo());
            if (oldApplyDO != null) {
                return ResponseUtils.buildFailResponse(String.valueOf(ErrorCodeEnum.ERROR_APPLY_IDCARD_SAME), "此身份证已经申请");
            }
        }


        final SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestUO2DO(request);
        SoldierBasicInfoDO baseInfo = soldierBasicInfoService.getSoldierBasicInfoByCard(request.getIdCardNo(), request.getRealName());
        if (baseInfo != null) {

            SoldierBasicInfoDO bySoldierId = soldierBasicInfoService.getBySoldierId(request.getSoldierId());
            if (bySoldierId != null) {
                bySoldierId.setSoldierId("");
                soldierBasicInfoService.update(bySoldierId);
            }
            if (Boolean.TRUE.equals(request.getHolded())) {
                soldierApplyInfoDO.setManualCheck(true);
                soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEALING.name());
            } else {
                baseInfo.setSoldierId(request.getSoldierId());
                baseInfo.setResidentAdminAreaCode(request.getResidentAdminAreaCode());
                baseInfo.setResidentAddress(request.getResidentAddress());
                baseInfo.setMobile(request.getMobile());
                baseInfo.setSoldierTypeDictCode(request.getSoldierTypeDictCode());
                baseInfo.setSoldierType(request.getSoldierType());
                baseInfo.setRetireDatetime(request.getRetireDatetime());
                baseInfo.setEntryDatetime(request.getEntryDatetime());
                baseInfo.setBirthday(request.getBirthday());
                soldierBasicInfoService.update(baseInfo);
                soldierApplyInfoDO.setManualCheck(false);
                soldierApplyInfoDO.setStatus(ProcessStatusEnum.SUCCESS.name());
            }

        } else {

            BizCheckUtil.checkNotBlank(request.getAttachment(), "附件不能为空");
            BizCheckUtil.checkIsTrue(!Boolean.TRUE.equals(request.getHolded()), "退役军人信息未采集");

            soldierApplyInfoDO.setManualCheck(true);
            soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEALING.name());
        }
        soldierApplyInfoDO.setId(applyInfoBySoldierId.getId());
        soldierApplyInfoDO.setApplyType(SoldierApplyTypeEnum.NORMAL.name());
        soldierApplyInfoDO.setCount(applyInfoBySoldierId.getCount() + 1);
        soldierApplyInfoService.update(soldierApplyInfoDO);
        return ResponseUtils.buildSuccessResponse(soldierApplyInfoDO.getId());
    }

    @Transactional
    @Override
    public BaseResponse<Boolean> completeTask(SoldierApplyInfoInsertRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getCondition(), "Condition不能为空");
        BizCheckUtil.checkNotNull(request.getId(), "id不能为空");
        SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.get(request.getId());
        if (SoldierApplyTypeEnum.NORMAL.name().equals(soldierApplyInfoDO.getApplyType()) || SoldierApplyTypeEnum.TEMPORARY.name().equals(soldierApplyInfoDO.getApplyType())) {
            if (!soldierApplyInfoDO.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
                return ResponseUtils.buildSuccessResponse(false);
            }
        }
        //审核之前权限判断
        if (SoldierApplyTypeEnum.OUTSIDER.name().equals(soldierApplyInfoDO.getApplyType())) {
            if (StringUtil.isNotEmpty(request.getCreatorId())) {
                List<GovEmployeeRoleDTO> roleDOList =  govEmployeeRoleProvider.getEmployeeRole(request.getCreatorId());
                log.info("获取角色List"+roleDOList.size());
                if(roleDOList != null && roleDOList.size()>0){
                    for(GovEmployeeRoleDTO govEmployeeRoleDO : roleDOList){
                        if(StringUtil.isNotEmpty(govEmployeeRoleDO.getCode())) {
                            if ("klhqxgzry".equals(govEmployeeRoleDO.getCode())) {
                                if (!request.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
                                    return ResponseUtils.buildFailResponse("当前登录用户没有审核权限");
                                }
                            }
                            if("klhbmfzr".equals(govEmployeeRoleDO.getCode())){
                                if(!request.getStatus().equals(ProcessStatusEnum.DEAL_WAIT.name())){
                                    return ResponseUtils.buildFailResponse("当前登录用户没有审核权限");
                                }
                            }
                            if("klhfgjld".equals(govEmployeeRoleDO.getCode())){
                                if(!request.getStatus().equals(ProcessStatusEnum.DEAL_FINAL.name())){
                                    return ResponseUtils.buildFailResponse("当前登录用户没有审核权限");
                                }
                            }
                        }
                    }
                }
            }
        }
        String comment = request.getComment();
        String condition = request.getCondition();
        if ("0".equals(condition)) {
            log.info("审核成功走这里");
            log.info("查询的applyType="+SoldierApplyTypeEnum.OUTSIDER.name());
            soldierApplyInfoDO.setAssignCodeTypeDictCode(request.getAssignCodeTypeDictCode());
            //判断赋码类型，老兵码+优待证需要判断且更新退军采集信息
            if ("2".equals(soldierApplyInfoDO.getAssignCodeTypeDictCode())) {
                //校验退役军人采集信息
                BizCheckUtil.checkNotNull(request.getBasicInformationDTO(), "退役军人采集信息不能为空");
                BizCheckUtil.checkNotBlank(request.getBasicInformationDTO().getCardpositive(), "优待证正面不能为空");
                BizCheckUtil.checkNotBlank(request.getBasicInformationDTO().getSuperiorcertificate(), "优待证反面不能为空");
                BizCheckUtil.checkNotBlank(request.getBasicInformationDTO().getPersonalphoto(), "近期个人照不能为空");

                //查询数据采集信息(优待证信息)
                BasicInformationDO qBasicInformationDO = new BasicInformationDO();
                qBasicInformationDO.setId(request.getBasicInformationDTO().getId());
                qBasicInformationDO.setIdCard(request.getIdCardNo());
                List<BasicInformationDO> basicInformationList = basicInformationService.queryBasicInformationList(qBasicInformationDO);
                if (CollectionUtils.isEmpty(basicInformationList)) {
                    throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR,  "该人员无采集信息无法赋优待码");
                }
                BasicInformationDO basicInformationDO = basicInformationList.get(0);
                basicInformationDO.setCardpositive(request.getBasicInformationDTO().getCardpositive());
                basicInformationDO.setSuperiorcertificate(request.getBasicInformationDTO().getSuperiorcertificate());
                basicInformationDO.setPersonalphoto(request.getBasicInformationDTO().getPersonalphoto());
                basicInformationService.updateBasicInformation(basicInformationDO);
            }

            if (SoldierApplyTypeEnum.OUTSIDER.name().equals(soldierApplyInfoDO.getApplyType())) {
                log.info("进常住老兵判断"+request.getStatus());
                //常住老兵审核3级状态
                if (request.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
                    log.info("设置审核状态1");
                    soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEAL_WAIT.name());
                }
                log.info("状态判断2"+request.getStatus());
                if(request.getStatus().equals(ProcessStatusEnum.DEAL_WAIT.name())){
                    log.info("设置审核状态2");
                    soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEAL_FINAL.name());
                }
                log.info("状态判断3"+request.getStatus());
                if(request.getStatus().equals(ProcessStatusEnum.DEAL_FINAL.name())){
                    log.info("设置审核状态3");
                    soldierApplyInfoDO.setStatus(ProcessStatusEnum.SUCCESS.name());
                }
                soldierApplyInfoDO.setIsPush("0");
            }else{
                log.info("进非常住老兵判断");
                soldierApplyInfoDO.setStatus(ProcessStatusEnum.SUCCESS.name());
                soldierApplyInfoDO.setComment(comment);
            }
            if (SoldierApplyTypeEnum.NORMAL.name().equals(soldierApplyInfoDO.getApplyType())) {
                soldierApplyInfoService.afterSoldierApplySucc(request.getId());
                sendApproveMessage(soldierApplyInfoDO.getSoldierId(), true, "审批通过");
            } else if (SoldierApplyTypeEnum.OUTSIDER.name().equals(soldierApplyInfoDO.getApplyType())) {
                //审核通过且是终审的时候走这里生成老兵码
                log.info("生成常住老兵码");
                if(request.getStatus().equals(ProcessStatusEnum.DEAL_FINAL.name())) {
                    SoldierOuterBasicInfoDO newSoldier = new SoldierOuterBasicInfoDO();
                    BeanUtils.copyProperties(soldierApplyInfoDO, newSoldier);
                    newSoldier.setCreateDatetime(new Date());
                    newSoldier.setModifyDatetime(new Date());
                    soldierOuterBasicInfoService.insert(newSoldier);
                    sendApproveMessage(soldierApplyInfoDO.getSoldierId(), true, "审批通过");
                }
            }
        } else {
            log.info("审核驳回走这里");
            soldierApplyInfoDO.setStatus(ProcessStatusEnum.REJECT.name());
            soldierApplyInfoDO.setComment(comment);
            sendApproveMessage(soldierApplyInfoDO.getSoldierId(), false, comment);
        }
        //添加审核流程
        if (SoldierApplyTypeEnum.OUTSIDER.name().equals(soldierApplyInfoDO.getApplyType())) {
            SoldierApplyCheckDO soldierApplyCheckDO = new SoldierApplyCheckDO();
            if (request.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
                //状态待初审 审核之后则为1级审核
                // 待初审-DEALING
                //待复审-DEAL_WAIT
                //待终审-DEAL_FINAL
                soldierApplyCheckDO.setLevel("1");
            }
            if(request.getStatus().equals(ProcessStatusEnum.DEAL_WAIT.name())){
                //状态待初审 审核之后则为2级审核
                soldierApplyCheckDO.setLevel("2");
            }
            if(request.getStatus().equals(ProcessStatusEnum.DEAL_FINAL.name())){
                soldierApplyCheckDO.setLevel("3");
            }
            if ("0".equals(condition)) { //审批通过
                soldierApplyCheckDO.setStatus("success");
            }else {   //审批驳回
                soldierApplyCheckDO.setStatus("reject");
            }
            soldierApplyCheckDO.setComments(comment);
            soldierApplyCheckDO.setApplyId(Long.valueOf(soldierApplyInfoDO.getId()));
            soldierApplyCheckDO.setCreatorId(request.getCreatorId());
            soldierApplyCheckDO.setCreatorName(request.getCreatorName());
            soldierApplyCheckDO.setCreateTime(new Date());
            soldierApplyCheckService.insert(soldierApplyCheckDO);
        }
        soldierApplyInfoDO.setModifyDatetime(new Date());
        soldierApplyInfoDO.setModifierId(request.getCreatorId());
        soldierApplyInfoDO.setModifierType(request.getCreatorType());
        log.info("更新前数据打印==="+soldierApplyInfoDO.getStatus());
        soldierApplyInfoService.update(soldierApplyInfoDO);

        if (SoldierApplyTypeEnum.NORMAL.name().equals(soldierApplyInfoDO.getStatus())) {
            soldierBasicRefresher.asyncRefreshAllBasicInfo(soldierApplyInfoDO.getIdCardNo());
        }

        return ResponseUtils.buildSuccessResponse(true);
    }

    private void sendApproveMessage(String soldierId, boolean b, String comment) {
        try {
            SoldierOuterLoginAccountDO account = soldierOuterLoginAccountService.getAccountDtoBySoldierId(soldierId);
            aliShhProvider.sendQrApproveResult(account.getOuterSysAccountId(), b, comment);
        } catch (Exception e) {
            log.error("{}", e);
        }
    }


    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> listWaitTask(SoldierApplyInfoSearchRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminCode(), "AdminCode不能为空");

        if (Strings.isBlank(request.getApplyType())) {
            request.setApplyType(SoldierApplyTypeEnum.NORMAL.name());
        }

        String cutdAreaCode = AdminAreaCodeUtils.getCutdAreaCode(request.getAdminCode());
        final SoldierApplyInfoBSearcher soldierApplyInfoBSearcher = SoldierApplyInfoProviderConverter.convertRequestSO2Searcher(request);
        soldierApplyInfoBSearcher.setResidentAdminAreaCode(cutdAreaCode);
        soldierApplyInfoBSearcher.setStatus(ProcessStatusEnum.DEALING.name());
        soldierApplyInfoBSearcher.setManualCheck(true);

        List<SoldierApplyInfoDO> soldierApplyInfoDOS = soldierApplyInfoService.searchByAreaLikeStatusManual(soldierApplyInfoBSearcher);

        List<SoldierApplyInfoDTO> remoteObj = SoldierApplyInfoProviderConverter.convertResponseDOList2DTOList(soldierApplyInfoDOS);
        for (SoldierApplyInfoDTO soldierApplyInfoDTO : remoteObj) {
            if (Strings.isBlank(soldierApplyInfoDTO.getRootAddress()) && !soldierApplyInfoDTO.getApplyType().equals(SoldierApplyTypeEnum.NORMAL.name())) {
                String fullValuePath = commonAdminAreaService.getQgFullValuePath(soldierApplyInfoDTO.getRootAdminAreaCode());
                soldierApplyInfoDTO.setRootAddress(fullValuePath);
            }

            if (soldierApplyInfoDTO.getApplyType().equals(SoldierApplyTypeEnum.TEMPORARY.name()) && Strings.isBlank(soldierApplyInfoDTO.getApplyStatus())) {
                int i = DateUtils.daysBetween(soldierApplyInfoDTO.getCreateDatetime(), new Date());
                if (i > 7) {
                    soldierApplyInfoDTO.setApplyStatus("EXPIRED");
                } else {
                    soldierApplyInfoDTO.setApplyStatus(String.valueOf(7 - i));
                }
            }
        }
        return ResponseUtils.buildSuccessPagingResponse(remoteObj, soldierApplyInfoBSearcher);
    }

    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> listDoneTask(SoldierApplyInfoSearchRequest request) {
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminCode(), "AdminCode不能为空");

        if (Strings.isBlank(request.getApplyType())) {
            request.setApplyType(SoldierApplyTypeEnum.NORMAL.name());
        }

        String cutdAreaCode = AdminAreaCodeUtils.getCutdAreaCode(request.getAdminCode());
        final SoldierApplyInfoBSearcher soldierApplyInfoBSearcher = SoldierApplyInfoProviderConverter.convertRequestSO2Searcher(request);
        soldierApplyInfoBSearcher.setResidentAdminAreaCode(cutdAreaCode);
        soldierApplyInfoBSearcher.setStatusList(Lists.newArrayList(ProcessStatusEnum.SUCCESS.name(), ProcessStatusEnum.REJECT.name()));

        List<SoldierApplyInfoDO> soldierApplyInfoDOS = soldierApplyInfoService.searchByAreaLikeAndStatusList(soldierApplyInfoBSearcher);

        List<SoldierApplyInfoDTO> remoteObj = SoldierApplyInfoProviderConverter.convertResponseDOList2DTOList(soldierApplyInfoDOS);
        for (SoldierApplyInfoDTO soldierApplyInfoDTO : remoteObj) {
            if (Strings.isBlank(soldierApplyInfoDTO.getRootAddress()) && !soldierApplyInfoDTO.getApplyType().equals(SoldierApplyTypeEnum.NORMAL.name())) {
                String fullValuePath = commonAdminAreaService.getQgFullValuePath(soldierApplyInfoDTO.getRootAdminAreaCode());
                soldierApplyInfoDTO.setRootAddress(fullValuePath);
            }

            if (soldierApplyInfoDTO.getApplyType().equals(SoldierApplyTypeEnum.TEMPORARY.name()) && Strings.isBlank(soldierApplyInfoDTO.getApplyStatus())) {
                int i = DateUtils.daysBetween(soldierApplyInfoDTO.getCreateDatetime(), new Date());
                if (i > 7) {
                    soldierApplyInfoDTO.setApplyStatus("EXPIRED");
                } else {
                    soldierApplyInfoDTO.setApplyStatus(String.valueOf(7 - i));
                }
            }
        }
        return ResponseUtils.buildSuccessPagingResponse(remoteObj, soldierApplyInfoBSearcher);
    }


    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> searchSoldierApplyInfo(final SoldierApplyInfoSearchRequest searchRequest) {

        final BasePagingResponse<List<SoldierApplyInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotNull(searchRequest.getEmail(), "查询分页SoldierApplyInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final SoldierApplyInfoBSearcher soldierApplyInfoBSearcher = SoldierApplyInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
                final List<SoldierApplyInfoDO> soldierApplyInfoDOList = soldierApplyInfoService.search(soldierApplyInfoBSearcher);
                final List<SoldierApplyInfoDTO> soldierApplyInfoDTOList = SoldierApplyInfoProviderConverter.convertResponseDOList2DTOList(soldierApplyInfoDOList);
                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, soldierApplyInfoDTOList, searchRequest, soldierApplyInfoBSearcher.getTotalCount());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_SEARCH;
            }
        });

        return basePagingResponse;
    }



    public BaseResponse<SoldierApplyInfoDTO> getSoldierApplyInfo(final BaseGetRequest baseGetRequest) {

        final BaseResponse<SoldierApplyInfoDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.get((String) baseGetRequest.getId());
                final SoldierApplyInfoDTO remoteObj = SoldierApplyInfoProviderConverter.convertResponseDO2DTO(soldierApplyInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_GET;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<String> insertSoldierApplyInfo(final SoldierApplyInfoInsertRequest insertRequest) {

        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增SoldierApplyInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestIO2DO(insertRequest);
                soldierApplyInfoService.insert(soldierApplyInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, soldierApplyInfoDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_INSERT;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> updateSoldierApplyInfo(final SoldierApplyInfoUpdateRequest updateRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierId(), "操作人不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");
            }

            @Override
            public void executeService() {
                SoldierApplyInfoDO soldierApplyInfoDO = SoldierApplyInfoProviderConverter.convertRequestUO2DO(updateRequest);
                Integer affectRowNum = soldierApplyInfoService.update(soldierApplyInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_UPDATE;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> deleteSoldierApplyInfo(final BaseDeleteRequest deleteRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(), "操作人类型不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getModifierId(), "操作人不能为空");
            }

            @Override
            public void executeService() {
                final Integer affectRowNum = soldierApplyInfoService.delete((String) deleteRequest.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> deleteUnsuccessfulApply(BaseDeleteRequest deleteRequest) {

        BizCheckUtil.checkNotNull(deleteRequest, "请求不能为空");
        BizCheckUtil.checkNotNull(deleteRequest.getId(), "id不能为空");

        String id = (String) deleteRequest.getId();
        SoldierApplyInfoDO applyInfoDO = soldierApplyInfoService.get(id);
        BizCheckUtil.checkNotNull(applyInfoDO, "不存在");
        if (applyInfoDO.getApplyType().equals(SoldierApplyTypeEnum.TEMPORARY.name())) {
            applyInfoDO.setApplyStatus("DELETE");
            soldierApplyInfoService.update(applyInfoDO);


            return ResponseUtils.buildSuccessResponse(0);
        }
        if (applyInfoDO.getApplyType().equals(SoldierApplyTypeEnum.OUTSIDER.name())) {
            soldierApplyCheckService.delete(applyInfoDO.getId());
            soldierApplyInfoService.delete(applyInfoDO.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
            soldierOuterBasicInfoService.deleteByIdCardNo(applyInfoDO.getIdCardNo());
            return ResponseUtils.buildSuccessResponse(0);
        }


        Integer i = soldierApplyInfoService.realDelete(id, deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
        SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getByIdCardNo(applyInfoDO.getIdCardNo());
        if (soldierBasicInfoDO != null) {
            final Integer affectRowNum = soldierBasicInfoService.delete((String) soldierBasicInfoDO.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
        }
        return ResponseUtils.buildSuccessResponse(i);
    }

    @Override
    public BaseResponse<ContactNoDTO> queryDistinctContactNo(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getAdminAreaCode(), "地区码不能为空");

        ContactNoDTO cachedContactNo = getCachedContactNo(request.getAdminAreaCode());
        return ResponseUtils.buildSuccessResponse(cachedContactNo);
    }





    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> searchCzApplyInfo(SoldierApplyInfoSearchRequest searchRequest) {
        BizCheckUtil.checkNotNull( searchRequest.getPageSize(), "pageSize不能为空");
        BizCheckUtil.checkNotNull( searchRequest.getPageNo(), "pageNo不能为空");
        final BasePagingResponse<List<SoldierApplyInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        final SoldierApplyInfoBSearcher soldierApplyInfoBSearcher = SoldierApplyInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
        soldierApplyInfoBSearcher.setApplyType("OUTSIDER");
        log.info("开始打印参数");
        if(soldierApplyInfoBSearcher != null && StringUtil.isNotEmpty(soldierApplyInfoBSearcher.getResidentAdminAreaCode())){
            log.info("行政区划不为空");
            if("330100000000".equals(soldierApplyInfoBSearcher.getResidentAdminAreaCode())){
                log.info("杭州市行政区划"+soldierApplyInfoBSearcher.getResidentAdminAreaCode().substring(0,4));
                soldierApplyInfoBSearcher.setResidentAdminAreaCode(soldierApplyInfoBSearcher.getResidentAdminAreaCode().substring(0,4));
            }else{
                log.info("非市本级行政区划"+soldierApplyInfoBSearcher.getResidentAdminAreaCode().substring(0,6));
                soldierApplyInfoBSearcher.setResidentAdminAreaCode(soldierApplyInfoBSearcher.getResidentAdminAreaCode().substring(0,6));
            }
        }
        log.info("soldierApplyInfoBSearcher实体的值"+soldierApplyInfoBSearcher);
        final List<SoldierApplyInfoDO> soldierApplyInfoDOList = soldierApplyInfoService.search(soldierApplyInfoBSearcher);
        final List<SoldierApplyInfoDTO> soldierApplyInfoDTOList = SoldierApplyInfoProviderConverter.convertResponseDOList2DTOList(soldierApplyInfoDOList);
        // 处理推送状态 未推送 已推送 推送失败
        for (SoldierApplyInfoDTO soldierApplyInfoDTO : soldierApplyInfoDTOList) {
            if ( !StringUtils.isEmpty(soldierApplyInfoDTO.getIsPush())) {
                if ("0".equals(soldierApplyInfoDTO.getIsPush())){
                    soldierApplyInfoDTO.setPushStatus("未推送");
                }
                if ("6".equals(soldierApplyInfoDTO.getIsPush())){
                    soldierApplyInfoDTO.setPushStatus("推送成功");
                }
                if ("2".equals(soldierApplyInfoDTO.getIsPush())){
                    soldierApplyInfoDTO.setPushStatus("推送失败");
                }
            }
        }
        return  ResponseUtils.buildSuccessPagingResponse(basePagingResponse, soldierApplyInfoDTOList, searchRequest, soldierApplyInfoBSearcher.getTotalCount());



    }

    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> searchAuditInfo(SoldierApplyInfoSearchRequest searchRequest) {
        BizCheckUtil.checkNotNull( searchRequest.getPageSize(), "pageSize不能为空");
        BizCheckUtil.checkNotNull( searchRequest.getPageNo(), "pageNo不能为空");
        final BasePagingResponse<List<SoldierApplyInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        final SoldierApplyInfoBSearcher soldierApplyInfoBSearcher = SoldierApplyInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
        List<SoldierApplyInfoDO> soldierApplyInfoDOList = new ArrayList<>();
        if (StringUtil.isNotEmpty(searchRequest.getGovUserId())) {
            log.info("进入权限判断方法");
            List<GovEmployeeRoleDTO> roleDOList =  govEmployeeRoleProvider.getEmployeeRole(searchRequest.getGovUserId());
            log.info("获取角色List"+roleDOList.size());
            if(roleDOList != null && roleDOList.size()>0){
                log.info("获取角色List>0");
                List<String> statusList = new ArrayList<>();   // 待初审-DEALING  待复审-DEAL_WAIT  待终审-DEAL_FINAL
                for(GovEmployeeRoleDTO govEmployeeRoleDO : roleDOList){
                    if(StringUtil.isNotEmpty(govEmployeeRoleDO.getCode())) {
                        if ("klhqxgzry".equals(govEmployeeRoleDO.getCode())) {
                            statusList.add("DEALING");
                        }
                        if("klhbmfzr".equals(govEmployeeRoleDO.getCode())){
                            statusList.add("DEAL_WAIT");
                        }
                        if("klhfgjld".equals(govEmployeeRoleDO.getCode())){
                            statusList.add("DEAL_FINAL");
                        }
                    }
                }
                log.info("根据角色判断状态statusList="+statusList);
                if(statusList != null && statusList.size()>0){
                    log.info("该用户有审批权限");
                    //根据当前登录用户获取其部门所在机构
                    List<GovOrgDTO> dto = govOrgProvider.listByEmployeeId(searchRequest.getGovUserId()).getDto();
                    if (dto != null && dto.size() > 0) {
                        log.info("获取adminAreaCode" + dto.get(0).getLeafAdminAreaId());
                        String adminAreaCode = dto.get(0).getLeafAdminAreaId();
                        if (StringUtil.isNotEmpty(adminAreaCode)) {
                            log.info("进入判空方法");
//                                        if (adminAreaCode.substring(0,6).equals("330100")){
//                                            log.info("是市本级行政区划");
//                                            searchRequest.setResidentAdminAreaCode(adminAreaCode.substring(0,4));
//                                        }else {
                            soldierApplyInfoBSearcher.setResidentAdminAreaCode(adminAreaCode.substring(0,6));
                            soldierApplyInfoBSearcher.setApplyType("OUTSIDER");
                            soldierApplyInfoBSearcher.setIsOnline("0");
                            log.info("查询传的参数statusList="+statusList);
                            soldierApplyInfoBSearcher.setStatusList(statusList);
                            //soldierApplyInfoBSearcher.setStatus("DEALING");
                            soldierApplyInfoDOList = soldierApplyInfoService.search(soldierApplyInfoBSearcher);

                        }
                    }
                }
            }
        }
        final List<SoldierApplyInfoDTO> soldierApplyInfoDTOList = SoldierApplyInfoProviderConverter.convertResponseDOList2DTOList(soldierApplyInfoDOList);
        return  ResponseUtils.buildSuccessPagingResponse(basePagingResponse, soldierApplyInfoDTOList, searchRequest, soldierApplyInfoBSearcher.getTotalCount());
    }

    @Override
    public BaseResponse<Boolean> updateSoldierApplyInfoAssignCode(SoldierApplyInfoAssignCodeUpdateRequest request) {
        SoldierApplyInfoDO soldierApplyInfoDO = soldierApplyInfoService.get(request.getId());
        BizCheckUtil.checkNotNull(soldierApplyInfoDO, "未查询到该申请记录");
        soldierApplyInfoDO.setAssignCodeTypeDictCode(request.getAssignCodeTypeDictCode());
        if ("2".equals(soldierApplyInfoDO.getAssignCodeTypeDictCode())) {
            //查询数据采集信息(优待证信息)
            BasicInformationDO qBasicInformationDO = new BasicInformationDO();
            qBasicInformationDO.setIdCard(soldierApplyInfoDO.getIdCardNo());
            List<BasicInformationDO> basicInformationList = basicInformationService.queryBasicInformationList(qBasicInformationDO);
            if (CollectionUtils.isEmpty(basicInformationList)) {
                throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR,  "该人员无采集信息无法赋优待码");
            }
            BasicInformationDO basicInformationDO = basicInformationList.get(0);
            BizCheckUtil.checkNotBlank(basicInformationDO.getCardpositive(), "优待证正面不能为空");
            BizCheckUtil.checkNotBlank(basicInformationDO.getSuperiorcertificate(), "优待证反面不能为空");
            BizCheckUtil.checkNotBlank(basicInformationDO.getPersonalphoto(), "近期个人照不能为空");
        }
        int i = soldierApplyInfoService.update(soldierApplyInfoDO);
        return com.insigma.business.qrcode.common.util.ResponseUtils.buildSuccessResponse(true);
    }

//    @Override
//    public BaseResponse<List<SoldierApplyCheckDTO>> getSoldierApplyCheckInfo(Long applyId) {
//        final BaseResponse<List<SoldierApplyCheckDTO>> baseResponse = new BaseResponse<>();
//        List<SoldierApplyCheckDTO> checkDOList =  soldierApplyInfoService.search(applyId);
//        return ResponseUtils.setupSuccessResponse(baseResponse, checkDOList);
//    }

//    @Override
//    public BaseResponse<String> insertSoldierApplyCheck(SoldierApplyCheckDTO soldierApplyCheckDO) {
//        Integer count = soldierApplyInfoService.insert(soldierApplyCheckDO);
//        return ResponseUtils.buildSuccessResponse(count+"");
//    }

    private String addResultStr(String reason, String name, String idCardNo) {
        return reason + "，姓名：" + name + "，身份证：" + idCardNo + "。\n";
    }


    private ContactNoDTO getCachedContactNo(String adminCode) {
        String prefixDistrictContactNo = "DISTRICT_CONTACT_NO_";
        String fillAreaCode = AdminAreaCodeUtils.fillAreaCode(adminCode.substring(0, 6));
        String key = prefixDistrictContactNo + fillAreaCode;

        String prefix = "REDIS_KEY";
        String redisKey = prefix + key;
        Object o = redisUtils.get(redisKey);
        if (o != null) {
            return (ContactNoDTO) o;
        }
        SystemConfigDO configDo = systemConfigService.getByName(key);
        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(adminCode);
        if (commonAdminAreaDO == null) {
            return null;
        }

        ContactNoDTO dto = new ContactNoDTO();
        dto.setAdminAreaCode(adminCode);
        dto.setAdminAreaValue(commonAdminAreaDO.getValue());
        if (configDo != null) {
            dto.setContactNo(configDo.getValue());
            dto.setRemark(configDo.getRemark());
            dto.setExtraInfo(configDo.getAdditionalValue());
        }

        SystemConfigDO telNo = systemConfigService.getByName("TECHNICAL_SUPPORT");
        if (telNo != null) {
            dto.setTechnicalSupportNo(telNo.getValue());
        }

        redisUtils.set(redisKey, dto, 60 * 60);
        return dto;
    }

    private void checkSoldierImportTemplate(List<Object> headers, String... names) {
        for (int i = 0; i < names.length; i++) {
            BizCheckUtil.checkIsTrue(((String) headers.get(i)).startsWith(names[i]), "模板错误");
        }
    }

    public static void main(String[] args) {
        SoldierApplyInfoDO soldierApplyInfoDO = new SoldierApplyInfoDO();
        soldierApplyInfoDO.setStatus("DEALING");
        if (soldierApplyInfoDO.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
            log.info("设置审核状态1");
            soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEAL_WAIT.name());
        }
        System.out.println(soldierApplyInfoDO.getStatus());
        if("DEAL_WAIT".equals(soldierApplyInfoDO.getStatus())){
            log.info("设置审核状态2");
            soldierApplyInfoDO.setStatus(ProcessStatusEnum.DEAL_FINAL.name());
        }
        if(soldierApplyInfoDO.getStatus().equals(ProcessStatusEnum.DEAL_FINAL.name())){
            log.info("设置审核状态3");
            soldierApplyInfoDO.setStatus(ProcessStatusEnum.SUCCESS.name());
        }
    }
}
